package com.lecture.java8.multithreading;

/**
 * @author luyn
 * @version 1.0
 * @description 生产者消费者应用
 * @date 2021/1/15 9:48
 */
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        producer p1 = new producer(clerk);
        p1.setName("生产者1");
        Consumer c1 = new Consumer(clerk);
        c1.setName("消费者1");
        p1.start();
        c1.start();
    }
}

class Clerk {

    private int num = 0;

    //生产产品
    public synchronized void produceProduct() {
        if (num < 20) {
            num ++;
            System.out.println(Thread.currentThread().getName() + "：开始生产第"+num+"个产品");
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //消费产品
  public synchronized void consumerProduct() {
        if (num > 0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "：开始消费第"+num+"个产品");
            num --;
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
  }
}
//生产者
class producer extends Thread {

    private Clerk clerk;

    public producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
                    clerk.produceProduct();
        }
    }
}

//消费者
class Consumer extends Thread {

    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.consumerProduct();
        }
    }
}